package com.ezbuy.common.request;


import com.ezbuy.common.error.BaseConsumer;
import com.ezbuy.common.error.ErrorConsumer;
import com.ezbuy.common.factory.ServiceFactory;
import com.ezbuy.common.functions.Consumer;
import com.ezbuy.common.functions.Mapper;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * yutianran 2018/12/1 下午12:15
 */
public class RxExecuter {

    public static <Request, Response> Disposable execute(Request request, final Consumer<Response> consumer, final Mapper<Request, Response> mapper) {
        return Observable.just(request)
                .map(new Function<Request, Response>() {
                    @Override
                    public Response apply(@NonNull Request request) throws Exception {
                        return mapper.map(request);
                    }
                })
                .compose(ObservableTransformerHelper.<Response>get())
                .subscribe(new io.reactivex.functions.Consumer<Response>() {
                    @Override
                    public void accept(Response response) throws Exception {
                        //这里将rx的Consumer接口,转换成我们自己的Consumer接口,是因为我们的Consumer接口可以兼容RpcRequest和GrpcRequest的请求方式
                        if (consumer != null) {
                            consumer.consume(response);
                        }
                    }
                }, new io.reactivex.functions.Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //如果有处理onError的BaseConsumer,就用BaseConsumer的onError处理
                        if (consumer != null && consumer instanceof BaseConsumer) {
                            System.out.println("自定义错误处理:" + throwable.getMessage());
                            BaseConsumer baseConsumer = (BaseConsumer) consumer;
                            baseConsumer.onError(throwable);
                            return;
                        }
                        //否则,就用注册在公共服务里面的ErrorConsumer的实现类处理
                        System.out.println("公共错误处理:" + throwable.getMessage());
                        ServiceFactory.getService(ErrorConsumer.class).onError(throwable);
                    }
                });
    }

    private static boolean isAndroidEnvironment() {
        try {
            Class<?> contextClass = Class.forName("android.content.Context");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }
}
